package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net"
	"time"

	reflectPb "gitee.com/wu-jin-feng/fgin/demos/fconsul_test/server/pb"
	"google.golang.org/grpc"
)

type DemoServiceServer struct {
	reflectPb.UnimplementedDemoServiceServer
}

func (s *DemoServiceServer) GetScheme(ctx context.Context, req *reflectPb.GetSchemeReq) (*reflectPb.GetSchemeResp, error) {
	if req.Info == nil {
		return nil, errors.New("info 不能为空")
	}
	fmt.Println("执行了方法, GetScheme")
	endData := &reflectPb.GetSchemeResp{
		Data: req.Path + ",gogogo",
		Info: &reflectPb.GetSchemeRespInfo{
			Info: fmt.Sprintf("这是一个info,%s", req.Info.Info),
			Name: fmt.Sprintf("作者是%s", req.Info.Name),
		},
	}
	return endData, nil
}

// 一元拦截器
func fgrpcInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		fmt.Println("fgrpcInterceptor")
		m, err := handler(ctx, req)
		fmt.Println("fgrpcInterceptor end", m, err)
		return m, err
	}
}

func fgrpcInterceptorV1() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		fmt.Println("fgrpcInterceptorV1")
		// return nil, fmt.Errorf("fgrpcInterceptorV1 异常")
		m, err := handler(ctx, req)
		fmt.Println("fgrpcInterceptorV1 end", m, err)
		return m, err
	}
}

func fgrpcInterceptorV2() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		fmt.Println("fgrpcInterceptorV2")
		m, err := handler(ctx, req)
		fmt.Println("fgrpcInterceptorV2 end", m, err)
		return m, err
	}
}

// 自定义创建grpc server
func newGrpcServer() *grpc.Server {
	opts := []grpc.ServerOption{}
	// 默认客户端5s没有完成连接，自动断开
	opts = append(opts, grpc.ConnectionTimeout(5*time.Second))
	// 添加拦截器
	opts = append(opts,
		grpc.ChainUnaryInterceptor(
			fgrpcInterceptor(),
			fgrpcInterceptorV1(),
		),
		grpc.UnaryInterceptor(fgrpcInterceptorV2()),
	)
	s := grpc.NewServer(opts...)
	return s
}

// 启动grpc
func runGrpc(s *grpc.Server) {
	address := "localhost:8090"
	listen, err := net.Listen("tcp", address)
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("grpc服务启动成功:%v\n", address)
	if err := s.Serve(listen); err != nil {
		log.Fatalf("listen: %v\n", err)
	}

}

func main() {
	s := newGrpcServer()
	reflectPb.RegisterDemoServiceServer(s, &DemoServiceServer{})
	runGrpc(s)
}
